// pages/cart/cart.js
var app = getApp();
var utils = require('../../utils/shop/formatShop.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    front_url: app.globalData.init.front_url,
    productsList: {},  //产品列表

    //记录删除产品的信息
    delArgs: {
      UsersID: '',
      User_ID: 0,
      action: 'cart_del',
      ProductsID: 0,
      CartID: 0,
      type:'cart'
    },

    //更新购物车产品数量
    update_cart_qty: {
      UsersID: '',
      User_ID: 0,
      action: 'cart_update',
      Type: '',       //qty_add(+)  qty_sub(-) change(input)
      ProductsID: 0,
      CartID: 0,
      Qty: 0,    //改变之前的数据（qty_add、qty_sub）  改变后的数据（change）
      type: 'cart'
    },

    totalQty: 0,  //产品总数量
    totalPrice: 0,  //产品总价

    submit_flag: true,    //提交状态

    loading_flag: true    //页面是能能加载（用于onShow的重复加载）
  },

  //去首页
  toIndex: function () {
    wx.switchTab({
      url: '../index/index'
    });
  },

  //去结算
  submit_cart: function () {
    if (this.data.totalQty > 0) {
      this.setData({
        submit_flag: false
      });
      wx.navigateTo({
        url: '../checkout/checkout?cart_key=CartList'
      });
    } else {
      wx.showModal({
        title: '提示',
        content: '购物车中无产品，去挑选产品',
        success: function (res) {
          if (res.confirm) {
            wx.redirectTo({
              url: '../index/index',
            });
          }
        }
      })
    }
  },

  //更新对应产品属性数量
  update_pro_qty: function (action, proid, attrid, qty) {
    this.setData({
      'update_cart_qty.UsersID': app.globalData.userInfo.Users_ID,
      'update_cart_qty.User_ID': app.globalData.userInfo.User_ID,
      'update_cart_qty.Type': action,
      'update_cart_qty.ProductsID': proid,
      'update_cart_qty.CartID': attrid,
      'update_cart_qty.Qty': qty
    });
    app.http_req(this.data.update_cart_qty, app.globalData.init.api_url, 'POST', this.updateCartQty);
  },

  //更新购物车产品数量回调
  updateCartQty: function (res) {
    if (res.status == 1 || res.status == 2) {
      if (res.status == 1) {
        wx.showModal({
          title: '提示',
          content: res.msg,
          showCancel: false
        });
      }
      //获取购物车信息
      var cartArgs = {
        UsersID: app.globalData.userInfo.Users_ID,
        User_ID: app.globalData.userInfo.User_ID ? app.globalData.userInfo.User_ID : 0,
        action: 'get_cart',
        cart_key: 'CartList',
        type: 'cart'
      };
      app.http_req(cartArgs, app.globalData.init.api_url, 'POST', this.getCartProduct);
    } else {
      wx.showModal({
        title: '提示',
        content: res.msg,
        showCancel: false
      });
    }
  },

  //减产品
  bindMinus: function (e) {
    var proid = e.currentTarget.dataset.proid;
    var attrid = e.currentTarget.dataset.attrid;
    var qty = e.currentTarget.dataset.qty;
    if (qty <= 1) {
      wx.showModal({
        title: '提示',
        content: '产品数量最小为1',
        showCancel: false
      });
      return false;
    }
    this.update_pro_qty('qty_sub', proid, attrid, qty);
  },

  //输入产品数量
  bindManual: function (e) {
    var proid = e.currentTarget.dataset.proid;
    var attrid = e.currentTarget.dataset.attrid;
    var qty = parseInt(e.detail.value);
    this.update_pro_qty('change', proid, attrid, qty);
  },

  //加产品
  bindPlus: function (e) {
    var proid = e.currentTarget.dataset.proid;
    var attrid = e.currentTarget.dataset.attrid;
    var qty = e.currentTarget.dataset.qty;
    this.update_pro_qty('qty_add', proid, attrid, qty);
  },

  //删除产品购物车产品
  del_cart_pro: function (e) {
    var that = this;
    var proid = e.currentTarget.dataset.proid;
    var attrid = e.currentTarget.dataset.attrid;
    wx.showModal({
      title: '提示',
      content: '确认将此产品从购物车中删除吗？',
      success: function (res) {
        if (res.confirm) {
          that.setData({
            'delArgs.UsersID': app.globalData.userInfo.Users_ID,
            'delArgs.User_ID': app.globalData.userInfo.User_ID,
            'delArgs.ProductsID': proid,
            'delArgs.CartID': attrid,
          });
          app.http_req(that.data.delArgs, app.globalData.init.api_url, 'POST', that.delCart);
        }
      }
    });
  },

  //删除购物车产品回调
  delCart: function (res) {
    if (res.status && (res.status == 1 || res.status == 3)) {
      wx.showToast({
        title: '删除成功',
        icon: 'success'
      });
    }
    //获取购物车信息
    var cartArgs = {
      UsersID: app.globalData.userInfo.Users_ID,
      User_ID: app.globalData.userInfo.User_ID ? app.globalData.userInfo.User_ID : 0,
      action: 'get_cart',
      cart_key: 'CartList',
      type: 'cart'
    };
    app.http_req(cartArgs, app.globalData.init.api_url, 'POST', this.getCartProduct);
  },

  //产品图片请求错误是显示默认图片
  show_default_proImg_cart: function (e) {
    var proid = e.currentTarget.dataset.proid;
    var attrid = e.currentTarget.dataset.attrid;
    this.setData({
      productsList: utils.show_default_proImg_cart(this.data.productsList, proid, attrid)
    });
  },

  //初始化本页展示的运费信息
  setShipping: function (res) {
    if (res.errorCode === 0) {
      this.setData({
        totalPrice: parseFloat(res.data.total_price)  //总价格展示
      })
    }
  },

  //获取购物车产品信息
  getCartProduct: function (res) {
    wx.hideLoading();
    if (res.errorCode == 0) {
      var productsList = res.data;
      //解析出属性
      for (var i in productsList) {
        for (var j in productsList[i]) {
          for (var k in productsList[i][j]['Property']) {
            var Name = productsList[i][j]['Property'][k]['Name'] ? productsList[i][j]['Property'][k]['Name'] : '';
            var Value = productsList[i][j]['Property'][k]['Value'] ? productsList[i][j]['Property'][k]['Value'] : '';
            if (Name != '' && Value != '') {
              var Name_arr = Name.split('|');
              var Value_arr = Value.split('|');
              var attr_name = '';
              for (var m in Name_arr) {
                attr_name += Name_arr[m] + ':' + Value_arr[m] + ' ';
              }
              productsList[i][j]['attrname'] = attr_name;
            }
          }
        }
      }
      this.setData({
        productsList: productsList,
        totalQty: utils.cart_pro(productsList, 'Qty')
      });
      //获取产品总价和运费
      var shippingArgs = {
        UsersID: app.globalData.userInfo.Users_ID,
        User_ID: app.globalData.userInfo.User_ID,
        action: 'get_shipping',
        cart_key: 'CartList',
        AddressID: 0,
        type: 'cart'
      };
      app.http_req(shippingArgs, app.globalData.init.api_url, 'POST', this.setShipping);
    } else if (res.errorCode == 2) {
      //购物车中无产品
      this.setData({
        productsList: {},
        totalQty: 0,
		    loading_flag: false
      });
    } else {
      wx.showModal({
        title: '错误',
        content: res.msg,
        showCancel: false
      });
    }
  },

  //页面加载
  load: function () {
    // 检查用户是否登录
    if (!app.globalData.userInfo) {
      app.login('', this.load, 'cart');
      return;
    }
    wx.showLoading({
      title: '加载中...'
    });
    //获取购物车信息
    var cartArgs = {
      UsersID: app.globalData.userInfo.Users_ID,
      User_ID: app.globalData.userInfo.User_ID ? app.globalData.userInfo.User_ID : 0,
      action: 'get_cart',
      cart_key: 'CartList',
      type: 'cart'
    };
    app.http_req(cartArgs, app.globalData.init.api_url, 'POST', this.getCartProduct);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //检查用户是否登录
    this.load();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({
      productsList: {},  //产品列表

      totalQty: 0,  //产品总数量
      totalPrice: 0,  //产品总价

      submit_flag: true,    //提交状态

      loading_flag: true    //页面是能能加载（用于onShow的重复加载）
    });
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  }
})